class PicturesController < PresentableController
	before_filter :find_model_instance, :only => [:show, :edit, :update, :destroy]
	after_filter :update_galleries, :only => [:create, :update]

  # GET /pictures
  # GET /pictures.xml
  def index
    @pictures = Picture.find_with_content :all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @pictures }
    end
  end

  # GET /pictures/1
  # GET /pictures/1.xml
  def show
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @picture }
    end
  end

  # GET /pictures/new
  # GET /pictures/new.xml
  def new
    @picture = Picture.new
    @user_groups_for_user = Lockdown::System.user_groups_assignable_for_user(current_user)

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @picture }
    end
  end

  # GET /pictures/1/edit
  def edit
    @user_groups_for_user = Lockdown::System.user_groups_assignable_for_user(current_user)
  end

  # POST /pictures
  # POST /pictures.xml
  def create
    @picture = Picture.new(params[:picture])

    respond_to do |format|
      if @picture.save
        flash[:notice] = 'Picture was successfully created.'
        format.html { redirect_to(@picture) }
        format.xml  { render :xml => @picture, :status => :created, :location => @picture }
      else
        logger.info(@picture.errors.inspect)
        @user_groups_for_user = Lockdown::System.user_groups_assignable_for_user(current_user)
        format.html { render :action => "new" }
        format.xml  { render :xml => @picture.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /pictures/1
  # PUT /pictures/1.xml
  def update
    respond_to do |format|
      if @picture.update_attributes(params[:picture])
        flash[:notice] = 'Picture was successfully updated.'
        format.html { redirect_to(@picture) }
        format.xml  { head :ok }
      else
        @user_groups_for_user = Lockdown::System.user_groups_assignable_for_user(current_user)
        format.html { render :action => "edit" }
        format.xml  { render :xml => @picture.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /pictures/1
  # DELETE /pictures/1.xml
  def destroy
    @picture.destroy

    respond_to do |format|
      format.html { redirect_to(pictures_url) }
      format.xml  { head :ok }
    end
  end

  private

  def find_model_instance
    @picture = Picture.find_with_content(params[:id])
  end

	def update_galleries
		new_gallery_ids = params.collect{|p| p[0].split("_")[1].to_i if p[0] =~ /^gal_/}.compact

		@picture.galleries.dup.each do |ug|
			unless new_gallery_ids.include?(ug.id)
				@picture.galleries.delete(ug) 
			end
		end

		new_gallery_ids.each do |id|
			next if @picture.gallery_ids.include?(id)
			@picture.galleries << Gallery.find(id)
		end
	end
end
